package com.acwer.drgs.performance.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.Map;

public abstract class GenerWord {
    private String tpl;
    public GenerWord(String tpl){
        this.tpl=tpl;
    }

    public void genger(HttpServletResponse rep,Map<String,Object> inps) throws Exception{
    // 1.获取报告模板
        ClassPathResource resource = new ClassPathResource(tpl);
        // 2.判断模板是否存在
        if (!resource.exists()) {
            throw new Exception(tpl+" 没找到！");
        }

        // 3.用数据填充模板
        InputStream wordTmpl = resource.getInputStream();

        // 获取单位名称
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(false);
        //生成参数
        Map<String, Object> params=generParams(inps);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        builder.bind("ls", policy);
        builder.bind("heightCostLs", policy);
        builder.bind("normalCost2ls", policy);
        builder.bind("normalCost3ls", policy);
        builder.bind("drgAllLs20", policy);
        builder.bind("zyysAllLs20", policy);
        builder.bind("cmigt2ls20", policy);

        XWPFTemplate template = XWPFTemplate.compile(wordTmpl, builder.build()).render(params);
        // 4.关闭模板文档
        wordTmpl.close();
        // 5.以网络流形式输出
        rep.setContentType("application/octet-stream");
        rep.setCharacterEncoding("UTF-8");

        String cpy="";
        if(inps.containsKey("cpy")) cpy=inps.get("cpy").toString();
        String fileName = downname(cpy);
        rep.setHeader("Content-disposition",
                "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1") + ".docx");
        // HttpServletResponse response
        OutputStream out = rep.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        template.close();

    }

    protected abstract String downname(String cpy);

    protected abstract Map<String,Object> generParams(Map<String,Object> inps) throws ParseException;
}
